/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package si.housing.javaadv.cl;

import java.lang.reflect.Method;
import java.util.Locale;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import si.housing.javaadv.cl.support.LoggingAspect;

/**
 * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
 */
public class TestJavassist
{
   public static void main(String[] args)
   {
      try
      {
         Object bean = modifyClass("si.housing.javaadv.support.MoreBeanImpl");
         Class<?> beanClass = bean.getClass();

         Method time = beanClass.getMethod("invokeSystemTime", Locale.class);
         System.out.println(time.invoke(bean, Locale.US));

         Method author = beanClass.getMethod("author");
         System.out.println(author.invoke(bean));
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }

   protected static Object modifyClass(String className) throws Exception
   {
      ClassPool pool = ClassPool.getDefault();
      CtClass ctClass = pool.getCtClass(className);

      // intercept methods
      CtMethod[] methods = ctClass.getDeclaredMethods();
      for (CtMethod method : methods)
      {
         method.insertBefore(LoggingAspect.class.getName() + ".before($0, \"" + method.getName() + "\");");
         method.insertAfter(LoggingAspect.class.getName() + ".after($0, \"" + method.getName() + "\");");
      }

      // adding author method
      CtMethod body = pool.getCtClass(LoggingAspect.class.getName()).getDeclaredMethod("author");
      CtMethod newMethod = CtNewMethod.delegator(body, ctClass);
      ctClass.addMethod(newMethod);

      // finally create new instance
      return ctClass.toClass().newInstance();
   }
}
